package com.sky.common.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.okhttp.OkDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;

import java.io.IOException;

/**
 * 容器客户端
 */
public class ContainerClient {

    /**
     * docker客户端
     */
    private final DockerClient     dockerClient;
    /**
     * docker http接口客户端
     */
    private final DockerHttpClient httpClient;

    /**
     * 构造器
     * @param host 主机
     * @param port 端口
     */
    public ContainerClient(String host, Integer port) {
        DockerClientConfig dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost("tcp://" + host + ":" + port)
                .withDockerTlsVerify(false).build();
        this.httpClient = new OkDockerHttpClient.Builder()
                .dockerHost(dockerClientConfig.getDockerHost())
                .sslConfig(dockerClientConfig.getSSLConfig())
                .build();
        this.dockerClient = DockerClientImpl.getInstance(dockerClientConfig, httpClient);
    }

    /**
     *  构造器
     * @param host 主机
     * @param port 端口
     * @param certPath 证书目录
     */
    public ContainerClient(String host, Integer port, String certPath) {
        DockerClientConfig dockerClientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
            .withDockerHost("tcp://" + host + ":" + port)
            .withDockerTlsVerify(true)
            .withDockerCertPath(certPath)
            .build();
        this.httpClient = new OkDockerHttpClient.Builder()
            .dockerHost(dockerClientConfig.getDockerHost())
            .sslConfig(dockerClientConfig.getSSLConfig())
            .build();
        this.dockerClient = DockerClientImpl.getInstance(dockerClientConfig, httpClient);
    }


    /**
     * 关闭
     */
    public void close() {
        try {
            dockerClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取docker客户端
     * @return docker客户端
     */
    public DockerClient getDockerClient() {
        return dockerClient;
    }
}
